package com.yangjun.service.bussiness;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.yangjun.common.DVConstants;
import com.yangjun.common.enums.ColorTypeEnum;
import com.yangjun.common.enums.OrderSourceTypeEnum;
import com.yangjun.common.enums.TimesTypeEnum;
import com.yangjun.dao.mybatis.mapper.businessAnalysis.MemberAnalysisMapper;

@Service
public class MemberAnalysisService {
    private final DecimalFormat doubleformat = new DecimalFormat("0.0000");
    @Autowired
    private MemberAnalysisMapper memberAnalysisMapper;
    /**
     * @Description 查询全司订单数，占比，增长率据根据下单间隔查询
     * @param orderIntervalArr
     * @return
     * @author yangjun
     * @Date 2016年10月22日 下午3:11:35
     */
    public Map<String,Object> getOrdersByOrderInterval(String[] orderIntervalArr,String siteName,String officeName){
        if(StringUtils.isNotEmpty(siteName)){
            siteName = OrderSourceTypeEnum.getOrderName(siteName);
        }
        //定义月份格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        Calendar calendar = Calendar.getInstance();
        String currentMon = df.format(calendar.getTime());
        calendar.add(Calendar.YEAR, -1);
        String dataDate = df.format(calendar.getTime());
        List<Map<String,Object>> ordersList = memberAnalysisMapper.queryOrdersByOrderInterval(dataDate,currentMon,siteName,officeName);
        String[] queryColumnArr = {"ORDER_1","ORDER_1_TO_2","ORDER_2_TO_3","ORDER_3_TO_6","ORDER_6_TO_12","ORDER_GREATER_12","ORDERS"};
        return getNumsAndProportion(orderIntervalArr,ordersList,queryColumnArr,DVConstants.ORDER_INTERVAL_NAME);
    }

    public Map<String,Object> getLastPurchaseSnapshot(String[] orderIntervalArr,String siteName,String officeName){
        if(StringUtils.isNotEmpty(siteName)){
            siteName = OrderSourceTypeEnum.getOrderName(siteName);
        }
        //定义月份格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        Calendar calendar = Calendar.getInstance();
        String currentMon = df.format(calendar.getTime());
        calendar.add(Calendar.YEAR, -1);
        String dataDate = df.format(calendar.getTime());
        List<Map<String,Object>> lastPurchaseMembersList = memberAnalysisMapper.queryLastPurchaseSnapshot(dataDate,currentMon,siteName,officeName);
        String[] queryColumnArr = {"MEMBER_1","MEMBER_1_TO_2","MEMBER_2_TO_3","MEMBER_3_TO_6","MEMBER_6_TO_12","MEMBER_GREATER_12","ALL_BUY_USERS"};
        return getNumsAndProportion(orderIntervalArr,lastPurchaseMembersList,queryColumnArr,DVConstants.ORDER_INTERVAL_NAME);
    }

    /**
     *
     * @Description 查询全司会员数，占比，增长率根据金额范围查询,近一年
     * @param moneyArr
     * @return
     * @author yangjun
     * @Date 2016年10月22日 下午3:05:59
     */
    public Map<String,Object> getRePurchaseByMoney(String[] moneyArr,String siteName,String officeName){
        if(StringUtils.isNotEmpty(siteName)){
            siteName = OrderSourceTypeEnum.getOrderName(siteName);
        }
        //定义月份格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        Calendar calendar = Calendar.getInstance();
        String currentMon = df.format(calendar.getTime());
        String dataDate = null;
        calendar.add(Calendar.YEAR, -1);
        dataDate = df.format(calendar.getTime());
        String[] queryColumnArr = {"MONEY_100","MONEY_100_TO_500","MONEY_500_T0_1000","MONEY_1000_TO_5000","MONEY_5000_TO_1W","MONEY_GREATER_1W","REPURCHASE_ALL_NUMS"};
        List<Map<String,Object>> rePurchaseByMoneyAndDateList = memberAnalysisMapper.queryRePurchaseByMoneyAndDate(dataDate,currentMon,siteName,officeName);
        return getNumsAndProportion(moneyArr,rePurchaseByMoneyAndDateList,queryColumnArr,DVConstants.RE_PURCHASE_MONEY_NAME);
    }

    /**
     * @Description查询全司会员数，占比，增长率根据次数时间范围查询,近一年
     * @param timesArr
     * @param flag
     * @author yangjun
     * @Date 2016年10月22日 下午1:55:52
     */
    public Map<String,Object> getRePurchaseByTimesAndDataDate(String[] timesArr,String siteName,String officeName){
        if(StringUtils.isNotEmpty(siteName)){
            siteName = OrderSourceTypeEnum.getOrderName(siteName);
        }
        //定义月份格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        Calendar calendar = Calendar.getInstance();
        String currentMon = df.format(calendar.getTime());
        String dataDate = null;
        List<Map<String,Object>> rePurchaseByTimesAndDateList = null;
        calendar.add(Calendar.YEAR, -1);
        dataDate = df.format(calendar.getTime());
        rePurchaseByTimesAndDateList = memberAnalysisMapper.queryRePurchaseByTimesAndDate(dataDate,currentMon,siteName,officeName);
        String[] queryColumnArr = {"ONE_TIMES","TWO_TIMES","THREE_TIMES","FOUR_TO_TEN_TIMES","ELEVEN_TO_TWENTY_TIMES","GREATER_TWENTY_TIMES","REPURCHASE_ALL_NUMS"};
        return getNumsAndProportion(timesArr,rePurchaseByTimesAndDateList,queryColumnArr,DVConstants.RE_PURCHASE_TIMES_NAME);
    }

    /**
     * @Description 默认false是查询最近一年，这是针对查询会员数，增长率以及占比的公共方法
     * @param timesArr
     * @param flag
     * @return
     * @author yangjun
     * @Date 2016年10月22日 上午11:32:33
     */
    private Map<String,Object> getNumsAndProportion(String[] timesArr,List<Map<String,Object>> list,String[] queryColumns,String[] titleArr){
        Map<String,Object> resultMap = Maps.newHashMap();
        //存放横坐标的集合
        List<String> dateList = Lists.newArrayList();
        //根据指标查询复购数据
        List<Map<String,Object>> targetList = list;
        String[] oneTimesArr = new String[12];
        String[] twoTimesArr = new String[12];
        String[] threeTimesArr = new String[12];
        String[] fourToTenTimesArr = new String[12];
        String[] elevenToTwentyTimesArr = new String[12];
        String[] greaterTwentyTimesArr = new String[12];

        String[] oneTimesProArr = new String[12];
        String[] twoTimesProArr = new String[12];
        String[] threeTimesProArr = new String[12];
        String[] fourToTenTimesProArr = new String[12];
        String[] elevenToTwentyTimesProArr = new String[12];
        String[] greaterTwentyTimesProArr = new String[12];
        //组装数据，每个次数对应一个List集合,表量级小已排序好
        for(int i=0,len=targetList.size();i<len;i++){
            Map<String,Object> targetDataMap = targetList.get(i);
//			System.out.println(targetDataMap);
//			if(targetDataMap.size()<2){
//				resultMap.put("nums", null);
//				resultMap.put("proportion", null);
//				resultMap.put("xAxis", null);
//				return resultMap;
//			}
            String one = targetDataMap.get(queryColumns[0])==null?"0":targetDataMap.get(queryColumns[0]).toString();
            String two = targetDataMap.get(queryColumns[1])==null?"0":targetDataMap.get(queryColumns[1]).toString();
            String three = targetDataMap.get(queryColumns[2])==null?"0":targetDataMap.get(queryColumns[2]).toString();
            String four_to_ten = targetDataMap.get(queryColumns[3])==null?"0":targetDataMap.get(queryColumns[3]).toString();
            String eleven_to_twenty = targetDataMap.get(queryColumns[4])==null?"0":targetDataMap.get(queryColumns[4]).toString();
            String greater_twenty = targetDataMap.get(queryColumns[5])==null?"0":targetDataMap.get(queryColumns[5]).toString();
            String data_date = targetDataMap.get("DATA_DATE").toString();
            String allNums = targetDataMap.get(queryColumns[6])==null?"0":targetDataMap.get(queryColumns[6]).toString();
            oneTimesArr[i]=one;
            twoTimesArr[i]=two;
            threeTimesArr[i]=three;
            fourToTenTimesArr[i]=four_to_ten;
            elevenToTwentyTimesArr[i]=eleven_to_twenty;
            greaterTwentyTimesArr[i]=greater_twenty;
            if(Integer.valueOf(allNums)!=0){
                if(StringUtils.isNotEmpty(one)){
                    oneTimesProArr[i]=doubleformat.format(Float.valueOf(one)/Integer.valueOf(allNums));
                }
                if(StringUtils.isNotEmpty(two)){
                    twoTimesProArr[i]=doubleformat.format(Float.valueOf(two)/Integer.valueOf(allNums));
                }
                if(StringUtils.isNotEmpty(three)){
                    threeTimesProArr[i]=doubleformat.format(Float.valueOf(three)/Integer.valueOf(allNums));
                }
                if(StringUtils.isNotEmpty(four_to_ten)){
                    fourToTenTimesProArr[i]=doubleformat.format(Float.valueOf(four_to_ten)/Integer.valueOf(allNums));
                }
                if(StringUtils.isNotEmpty(eleven_to_twenty)){
                    elevenToTwentyTimesProArr[i]=doubleformat.format(Float.valueOf(eleven_to_twenty)/Integer.valueOf(allNums));
                }
                if(StringUtils.isNotEmpty(greater_twenty)){
                    greaterTwentyTimesProArr[i]=doubleformat.format(Float.valueOf(greater_twenty)/Integer.valueOf(allNums));
                }
            }else{
                oneTimesProArr[i]="0";
                twoTimesProArr[i]="0";
                threeTimesProArr[i]="0";
                fourToTenTimesProArr[i]="0";
                elevenToTwentyTimesProArr[i]="0";
                greaterTwentyTimesProArr[i]="0";
            }

            dateList.add(data_date);
        }
        Map<String,Object> timesMap =  Maps.newHashMap();
        Map<String,Object> proportionMap =  Maps.newHashMap();
        for(int i=0,len=timesArr.length;i<len;i++){
            String str = timesArr[i];
            if("one".equals(str)){
                timesMap.put(str, handleDataMap(str,oneTimesArr,titleArr));
                proportionMap.put(str, handleDataMap(str,oneTimesProArr,titleArr));
            }
            if("two".equals(str)){
                timesMap.put(str, handleDataMap(str,twoTimesArr,titleArr));
                proportionMap.put(str, handleDataMap(str,twoTimesProArr,titleArr));
            }
            if("three".equals(str)){
                timesMap.put(str, handleDataMap(str,threeTimesArr,titleArr));
                proportionMap.put(str, handleDataMap(str,threeTimesProArr,titleArr));
            }
            if("four".equals(str)){
                timesMap.put(str, handleDataMap(str,fourToTenTimesArr,titleArr));
                proportionMap.put(str, handleDataMap(str,fourToTenTimesProArr,titleArr));
            }
            if("five".equals(str)){
                timesMap.put(str, handleDataMap(str,elevenToTwentyTimesArr,titleArr));
                proportionMap.put(str, handleDataMap(str,elevenToTwentyTimesProArr,titleArr));
            }
            if("six".equals(str)){
                timesMap.put(str, handleDataMap(str,greaterTwentyTimesArr,titleArr));
                proportionMap.put(str, handleDataMap(str,greaterTwentyTimesProArr,titleArr));
            }
        }
        resultMap.put("nums", timesMap);
        resultMap.put("proportion", proportionMap);
        resultMap.put("xAxis", dateList);
        return resultMap;
    }
    private Map<String,Object> handleDataMap(String times,String[] timesArr,String[] titleArr){
        Map<String,Object> dataMap =  Maps.newHashMap();
        dataMap.put("name", titleArr[TimesTypeEnum.getId(times)]);
        dataMap.put("color", ColorTypeEnum.getColorType(times));
        dataMap.put("data", timesArr);
        return dataMap;
    }
    /***
     * @Description 查询全司历史会员数根据最后购买时间查询以及占比
     * @return
     * @author yangjun
     * @Date 2016年10月21日 下午3:10:33
     */
    public Map<String,Object> getLastPurchaseMembersByOrderInterval(String siteName,String officeName){
        if(StringUtils.isNotEmpty(siteName)){
            siteName = OrderSourceTypeEnum.getOrderName(siteName);
        }
        String[] queryColumnArr = {"MEMBER_1","MEMBER_1_TO_2","MEMBER_2_TO_3","MEMBER_3_TO_6","MEMBER_6_TO_12","MEMBER_GREATER_12"};
        Map<String,Object> lastPurchaseMembersByOrderIntervalMap = memberAnalysisMapper.queryLastPurchaseMembersByOrderInterval(siteName,officeName);
        return handleNumsAndRate(queryColumnArr,lastPurchaseMembersByOrderIntervalMap);
    }

    /***
     * @Description 查询全司历史订单数根据订单间隔查询以及占比
     * @return
     * @author yangjun
     * @Date 2016年10月21日 下午3:10:33
     */
    public Map<String,Object> getHistoryOrdersByOrderInterval(String siteName,String officeName){
        if(StringUtils.isNotEmpty(siteName)){
            siteName = OrderSourceTypeEnum.getOrderName(siteName);
        }
        String[] queryColumnArr = {"ORDER_1","ORDER_1_TO_2","ORDER_2_TO_3","ORDER_3_TO_6","ORDER_6_TO_12","ORDER_GREATER_12"};
        Map<String,Object> historyOrdersByOrderIntervalList = memberAnalysisMapper.queryHistoryOrdersByOrderInterval(siteName,officeName);
        return handleNumsAndRate(queryColumnArr,historyOrdersByOrderIntervalList);
    }
    /***
     * @Description 查询全司复购不同金额的会员数以及占比
     * @return
     * @author yangjun
     * @Date 2016年10月21日 下午3:10:33
     */
    public Map<String,Object> getAllRePurchaseByMoney(String siteName,String officeName){
        if(StringUtils.isNotEmpty(siteName)){
            siteName = OrderSourceTypeEnum.getOrderName(siteName);
        }
        String[] queryColumnArr = {"MONEY_100","MONEY_100_TO_500","MONEY_500_T0_1000","MONEY_1000_TO_5000","MONEY_5000_TO_1W","MONEY_GREATER_1W"};
        Map<String,Object> RePuchaseMoneyList = memberAnalysisMapper.queryRePurchaseByMoney(siteName,officeName);
        return handleNumsAndRate(queryColumnArr,RePuchaseMoneyList);
    }
    /***
     * @Description 查询全司不同复购次数的会员数以及占比
     * @return
     * @author yangjun
     * @Date 2016年10月21日 下午3:10:33
     */
    public Map<String,Object> getAllRePurchaseByTimes(String siteName,String officeName){
        if(StringUtils.isNotEmpty(siteName)){
            siteName = OrderSourceTypeEnum.getOrderName(siteName);
        }
        String[] queryColumnArr = {"ONE_TIMES","TWO_TIMES","THREE_TIMES","FOUR_TO_TEN_TIMES","ELEVEN_TO_TWENTY_TIMES","GREATER_TWENTY_TIMES"};
        Map<String,Object> RePuchaseTimesMap = memberAnalysisMapper.queryRePurchaseByTimes(siteName,officeName);
        return handleNumsAndRate(queryColumnArr,RePuchaseTimesMap);
    }
    /**
     * @Description 专门处理类似只有数目占比的表格的公共方法
     * @param titleArr
     * @param list
     * @param queryColumns
     * @author yangjun
     * @Date 2016年10月22日 下午3:29:23
     */
    private Map<String,Object> handleNumsAndRate(String[] queryColumns,Map<String,Object> map){
        Map<String,Object> resultMap = Maps.newHashMap();
        int[] numsArr = new int[6];
        float[] rateArr = new float[6];
        if(map!=null){
            numsArr[0] = map.get(queryColumns[0])==null?0:Integer.valueOf(map.get(queryColumns[0]).toString());
            numsArr[1] = map.get(queryColumns[1])==null?0:Integer.valueOf(map.get(queryColumns[1]).toString());
            numsArr[2] = map.get(queryColumns[2])==null?0:Integer.valueOf(map.get(queryColumns[2]).toString());
            numsArr[3] = map.get(queryColumns[3])==null?0:Integer.valueOf(map.get(queryColumns[3]).toString());
            numsArr[4] = map.get(queryColumns[4])==null?0:Integer.valueOf(map.get(queryColumns[4]).toString());
            numsArr[5] = map.get(queryColumns[5])==null?0:Integer.valueOf(map.get(queryColumns[5]).toString());
            int sum = Integer.valueOf(numsArr[0])+Integer.valueOf(numsArr[1])
                    +Integer.valueOf(numsArr[2])+Integer.valueOf(numsArr[3])
                    +Integer.valueOf(numsArr[4])+Integer.valueOf(numsArr[5]);
            for(int i=0,len=numsArr.length;i<len;i++){
                rateArr[i]=Float.valueOf(doubleformat.format(Integer.valueOf(numsArr[i])/(float)sum));
            }
        }
        resultMap.put("nums", numsArr);
        resultMap.put("rate", rateArr);
        return resultMap;
    }
    /**
     * @Description 获取最近两年每月新增会员数
     * @return
     * @author yangjun
     * @Date 2016年10月20日 下午5:10:05
     */
    public Map<String,Object> recentTwoYearIncreasedMember(String siteName,String officeName){
        Calendar calendar = Calendar.getInstance();
        String thisYear = String.valueOf(calendar.get(calendar.YEAR));
        if(StringUtils.isNotEmpty(siteName)){
            siteName = OrderSourceTypeEnum.getOrderName(siteName);
        }
        String lastYear = String.valueOf(Integer.valueOf(thisYear)-1);
        String last2Year = String.valueOf(Integer.valueOf(thisYear)-2);
        String[] yearArr = new String[]{thisYear,lastYear};
        List<Map<String,Object>> recentTwoYearList = memberAnalysisMapper.queryRecentTwoYearIncreasedMemberByMonth(yearArr,last2Year,siteName,officeName);
        return handleTwoBarIncreaseData("YEAR","MONTH",DVConstants.MONTH,thisYear,lastYear,recentTwoYearList,DVConstants.MONTH_ARR_NAME);
    }
    /**
     * @Description 获取最近两年每月复购会员数
     * @return
     * @author yangjun
     * @Date 2016年10月20日 下午5:10:05
     */
    public Map<String,Object> recentTwoYearRePurchaseMember(String siteName,String officeName){
        Calendar calendar = Calendar.getInstance();
        String thisYear = String.valueOf(calendar.get(calendar.YEAR));
        if(StringUtils.isNotEmpty(siteName)){
            siteName = OrderSourceTypeEnum.getOrderName(siteName);
        }
        String lastYear = String.valueOf(Integer.valueOf(thisYear)-1);
        String[] yearArr = new String[]{thisYear,lastYear};
        List<Map<String,Object>> recentTwoYearList = memberAnalysisMapper.queryRecentTwoYearRePurchaseMemberByMonth(yearArr,siteName,officeName);
        return handleTwoBarRePurchaseData("YEAR","MONTH",DVConstants.MONTH,thisYear,lastYear,recentTwoYearList,DVConstants.MONTH_ARR_NAME);
    }
    public  Map<String,Object> handleTwoBarRePurchaseData (String legendColumn,String xAxisColumn,String[] xAxisArr,String current,String contrast,List<Map<String,Object>> recentTwoYearList,String[] barxAxisName){
        Map<String,Object> resutlMap = Maps.newHashMap();
        String[] currentDataArr = new String[xAxisArr.length];
        String[] contrastDataArr = new String[xAxisArr.length];
        String[] currentDataRePurchaseRate = new String[xAxisArr.length];
        String[] contrastDataRePurchaseRate = new String[xAxisArr.length];
        String legend = null;
        String xAxis = null;
        String nums = null;
        String rePurchaseRate = null;

        for(Map<String,Object> yearMap : recentTwoYearList){
            legend = yearMap.get(legendColumn).toString();
            xAxis = yearMap.get(xAxisColumn).toString();
            nums = yearMap.get("NUMS").toString();
            rePurchaseRate = yearMap.get("RATE").toString();
            for(int i=0,len=xAxisArr.length;i<len;i++){
                //有些月份0开头有些月份不是，后面需要规范格式
                if(xAxis.equals(xAxisArr[i])){
                    if(current.equals(legend)){
                        currentDataArr[i]=nums;
                        currentDataRePurchaseRate[i]=rePurchaseRate;
                    }else if(contrast.equals(legend)){
                        contrastDataArr[i]=nums;
                        contrastDataRePurchaseRate[i]=rePurchaseRate;
                    }
                    break;
                }
            }
        }
        resutlMap.put("currentDataRePurchaseRate", currentDataRePurchaseRate);
        resutlMap.put("contrastDataRePurchaseRate", contrastDataRePurchaseRate);
        resutlMap.put("currentDataArr", currentDataArr);
        resutlMap.put("contrastDataArr", contrastDataArr);
        resutlMap.put("xAxis", barxAxisName);
        return resutlMap;
    }

    /**
     * @Description 专门处理非对比的饼图
     * @param legendColumn
     * @param legendArr
     * @param dataList
     * @param pieName
     * @param pieLegendName
     * @return
     * @author yangjun
     * @Date 2016年10月24日 下午3:16:19
     */
    private Map<String,Object> handlePieData(List<Map<String,Object>> list,String legendColumn,String legendName){
        Map<String,Object> resultMap = Maps.newHashMap();
        String name = null;
        String value = null;
        List<String> lengendList = Lists.newArrayList();
        List<Map<String,String>> dataList = Lists.newArrayList();
        Collections.sort(list,new Comparator<Map<String,Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                return o1.get("NUMS").toString().compareTo(o2.get("NUMS").toString());
            }
        });
        for(Map<String,Object> officesMemberMap : list){
            Map<String,String> dataMap = Maps.newHashMap();
            name = officesMemberMap.get(legendColumn).toString();
            value = officesMemberMap.get("NUMS").toString();
            lengendList.add(name);
            dataMap.put("name", name);
            dataMap.put("value", value);
            dataList.add(dataMap);
        }
        resultMap.put("data", dataList);
        resultMap.put("lengend", lengendList);
        resultMap.put("name",legendName);
        return resultMap;
    }
    /**
     * @Description 专门处理对比的饼图
     * @param legendColumn
     * @param xAxisColumn
     * @param recentTwoDayList
     * @param legendArr
     * @param current
     * @param contrast
     * @param pieName
     * @param pieLegend
     * @author yangjun
     * @Date 2016年10月24日 上午10:38:22
     */
    private Map<String,Object> handlePieData(String NameColumn,String legendColumn,String[] legendArr,String current,String contrast,List<Map<String,Object>> recentTwoDayList,String pieName,String[] pieLegendName){
        Map<String,Object> resutlMap = Maps.newHashMap();
        List<Map<String,String>> currentDataList = Lists.newArrayList();
        List<Map<String,String>> contrastDataList = Lists.newArrayList();
        List<Map<String,String>> sortContrastDataList = Lists.newArrayList();
        String[] sortPieLegendName = new String[pieLegendName.length*2];
        String name = null,legend = null,nums = null;
        for(Map<String,Object> dayMap : recentTwoDayList){
            name = dayMap.get(NameColumn).toString();
            legend = dayMap.get(legendColumn).toString();
            nums = dayMap.get("NUMS").toString();
            for(int i=0,len=legendArr.length;i<len;i++){
                //有些月份0开头有些月份不是，后面需要规范格式
                if(legend.equals(legendArr[i])||legend.equals("0"+legendArr[i])){
                    if(current.equals(name)){
                        Map<String,String> currentDataMap = Maps.newHashMap();
                        currentDataMap.put("name", "今日："+pieLegendName[i]);
                        currentDataMap.put("value", nums);
                        currentDataList.add(currentDataMap);
                    }else if(contrast.equals(name)){
                        Map<String,String> contrastDataMap = Maps.newHashMap();
                        contrastDataMap.put("name", "昨日："+pieLegendName[i]);
                        contrastDataMap.put("value", nums);
                        contrastDataList.add(contrastDataMap);
                    }
                    break;
                }
            }
        }
        Collections.sort(currentDataList,new Comparator<Map<String,String>>() {
            @Override
            public int compare(Map<String, String> map1, Map<String, String> map2) {
                int n1 = Integer.valueOf(map1.get("value"));
                int n2 = Integer.valueOf(map2.get("value"));
                if(n1<n2){
                    return 1;
                }else if(n1>n2){
                    return -1;
                }else{
                    return 0;
                }
            }
        });

        for(Map<String,String> tmpCurrentMap : currentDataList){
            String currentName = tmpCurrentMap.get("name").substring(3);
            for(Map<String,String> tmpContrastMap : contrastDataList){
                String contrastName = tmpContrastMap.get("name").substring(3);
                if(currentName.equals(contrastName)){
                    sortContrastDataList.add(tmpContrastMap);
                    break;
                }
            }
        }
        for(int i=0,len=pieLegendName.length;i<len;i++){
            sortPieLegendName[i]="今日："+pieLegendName[i];
            sortPieLegendName[i+pieLegendName.length]="昨日："+pieLegendName[i];

        }
        resutlMap.put("currentData", currentDataList);
        resutlMap.put("contrastData", sortContrastDataList);
        resutlMap.put("name", pieName);
        resutlMap.put("legend", sortPieLegendName);
        return resutlMap;
    }
    /**
     * @Description 专门处理对比的柱状图，可以根据flag来判断是否计算增长率和增长
     * @param legendColumn
     * @param xAxisColumn
     * @param xAxisArr
     * @param current
     * @param contrast
     * @param recentTwoYearList
     * @author yangjun
     * @Date 2016年10月22日 下午4:35:27
     */
    public  Map<String,Object> handleTwoBarIncreaseData (String legendColumn,String xAxisColumn,String[] xAxisArr,String current,String contrast,List<Map<String,Object>> recentTwoYearList,String[] barxAxisName){
        Map<String,Object> resutlMap = Maps.newHashMap();
        String[] currentDataArr = new String[xAxisArr.length];
        String[] contrastDataArr = new String[xAxisArr.length];

        String legend = null;
        String xAxis = null;
        String nums = null;
        List<String> increaseList = Lists.newArrayList();
        for(Map<String,Object> yearMap : recentTwoYearList){
            legend = yearMap.get(legendColumn).toString();
            xAxis = yearMap.get(xAxisColumn).toString();
            nums = yearMap.get("NUMS").toString();
            for(int i=0,len=xAxisArr.length;i<len;i++){
                //有些月份0开头有些月份不是，后面需要规范格式
                if(xAxis.equals(xAxisArr[i])||xAxis.equals("0"+xAxisArr[i])){
                    if(current.equals(legend)){
                        currentDataArr[i]=nums;
                    }else if(contrast.equals(legend)){
                        contrastDataArr[i]=nums;
                    }
                    break;
                }
            }
            if(!current.equals(legend)&&!contrast.equals(legend)){
                increaseList.add(nums);
            }
        }
        String[] currentDataIncreaseRate = new String[xAxisArr.length];
        String[] contrastDataIncreaseRate = new String[xAxisArr.length];
        //处理增长数和增长率
        increaseList.addAll(Arrays.asList(contrastDataArr));
        increaseList.addAll(Arrays.asList(currentDataArr));
        String[] increaseArr = new String[25];
        int index = 0;
        for(String str : increaseList){
            increaseArr[index++]=str;
        }
        for(int i=0,len=increaseArr.length;i<len;i++){
            if(i>0){
                if(StringUtils.isNotEmpty(increaseArr[i])){
                    int thisNum = Integer.valueOf(increaseArr[i]);
                    int lastNum = 0;
                    String increaseRate = null;
                    if(StringUtils.isNotEmpty(increaseArr[i-1])){
                        lastNum = Integer.valueOf(increaseArr[i-1]);
                        increaseRate = doubleformat.format((float)(thisNum-lastNum)/lastNum);
                    }
                    if(i<13){
                        contrastDataIncreaseRate[i-1]=increaseRate;
                    }else{
                        currentDataIncreaseRate[i-13]=increaseRate;
                    }
                }
            }
        }
        resutlMap.put("currentDataIncreaseRate", currentDataIncreaseRate);
        resutlMap.put("contrastDataIncreaseRate", contrastDataIncreaseRate);

        resutlMap.put("currentDataArr", currentDataArr);
        resutlMap.put("contrastDataArr", contrastDataArr);
        resutlMap.put("xAxis", barxAxisName);
        return resutlMap;
    }

    /**
     *
     * @Description 历史每年每月会员数(可以根据平台，科室进行选择)
     * @param orderSourceName
     * @param officeName
     * @return
     * @author yangjun
     * @Date 2016年10月20日 下午1:59:42
     */
    public Map<String,Object> getAllIncreasedMemberByMonth(String siteName,String officeName){
        if(StringUtils.isNotEmpty(siteName)){
            siteName = OrderSourceTypeEnum.getOrderName(siteName);
        }
        Map<String,Object> increasedMemberResultMap = Maps.newTreeMap();
        //根据flag设置不同平台或不同科室的map，存放每一年的会员数
        Map<String,List<Map<String, String>>> orderSourceOrOfficesMap = Maps.newTreeMap();
        String year = null;
        String month = null;
        String nums = null;
        List<String[]> memberNumsByOrderSourceList = Lists.newArrayList();
        List<Map<String,Object>> queryMemberList = memberAnalysisMapper.queryAllIncreasedMemberByMonth(siteName,officeName);
        String[] monthArr = DVConstants.MONTH;
        //组装成：年为key,每个月对应的新增会员数的list作为value
        for(Map<String,Object> increasedMemberMap : queryMemberList){
            Map<String,String> tmpMap = Maps.newHashMap();
            year = increasedMemberMap.get("YEAR").toString();//年
            month = increasedMemberMap.get("MONTH").toString();//月
            nums = increasedMemberMap.get("NUMS").toString();//新增会员数
            tmpMap.put("nums", nums);
            tmpMap.put("month", month);
            List<Map<String,String>> tmpList = orderSourceOrOfficesMap.get(year);
            if(tmpList==null){
                tmpList = Lists.newArrayList();
                tmpList.add(tmpMap);
            }else{
                tmpList.add(tmpMap);
            }
            orderSourceOrOfficesMap.put(year, tmpList);
        }

        for(Map.Entry<String,List<Map<String, String>>> entry :orderSourceOrOfficesMap.entrySet()){
            List<Map<String, String>> dataList = entry.getValue();
            Map<String,String> NumsMap = Maps.newHashMap();
            int sum = 0;
            //存放该年每个月的会员数
            for(Map<String, String> dataMap: dataList){
                NumsMap.put(dataMap.get("month"),dataMap.get("nums"));
            }
            //从第三列才是具体每个月的数据
            String[] DataArr = new String[monthArr.length+2];
            DataArr[0] = entry.getKey();
            //有些平台可能该月没有新增会员则置为零
            for(int i = 0,len=monthArr.length ;i < len;i++ ){
                String members = NumsMap.get(monthArr[i]);
                if(StringUtils.isNotEmpty(members)){
                    DataArr[i+2] = members;
                }else{
                    DataArr[i+2] = "0";
                }
            }
            //每个月的求和
            for(int i = 2,len=DataArr.length ;i < len;i++ ){
                sum += Integer.valueOf(DataArr[i]);
            }
            DataArr[1] = String.valueOf(sum);
            //组装平台数据
            memberNumsByOrderSourceList.add(DataArr);
        }
        Collections.sort(memberNumsByOrderSourceList,new Comparator<String[]>() {
            @Override
            public int compare(String[] o1, String[] o2) {
                if(Integer.valueOf(o1[0])>Integer.valueOf(o2[0])){
                    return -1;
                }else if(Integer.valueOf(o1[0])<Integer.valueOf(o2[0])){
                    return 1;
                }else{
                    return 0;
                }
            }
        });
        increasedMemberResultMap.put("data", memberNumsByOrderSourceList);
        return increasedMemberResultMap;
    }

    /**
     * @Description 全科室的历史新增会员饼图
     * @return
     * @author yangjun
     * @Date 2016年10月20日 上午11:49:49
     */
    public Map<String,Object> getOfficesMember(String siteName){
        if(StringUtils.isNotEmpty(siteName)){
            siteName = OrderSourceTypeEnum.getOrderName(siteName);
        }
        List<Map<String,Object>> officesMemberList = memberAnalysisMapper.queryOfficesMember(siteName);
        return handlePieData(officesMemberList,"TYPENAME",DVConstants.MEMBER_LEGEND_NAME);
    }
    /**
     * @Description 获取全司历史新增会员数
     * @return
     * @author yangjun
     * @Date 2016年10月20日 上午9:54:42
     */
    public Map<String,Object> getAllIncreasedMember(String siteName,String officeName){
        if(StringUtils.isNotEmpty(siteName)){
            siteName = OrderSourceTypeEnum.getOrderName(siteName);
        }
        List<Map<String,Object>> allIncreasedMemberList = memberAnalysisMapper.queryAllIncreasedMember(siteName,officeName);
        return handleIncreasedMemberEveryYear(allIncreasedMemberList);
    }
    public Map<String,Object> handleIncreasedMemberEveryYear(List<Map<String,Object>> list){
        Map<String,Object> resultMap = Maps.newHashMap();
        Map<String,String> dataMap = Maps.newHashMap();
        //排序好的set集合用来存放年份
        Set<String> yearSet = Sets.newTreeSet();
        String year = null;
        String nums = null;
        int sum = 0;
        for(Map<String,Object> tmpMap : list){
            year = tmpMap.get("YEAR").toString();
            nums = tmpMap.get("NUMS").toString();
            yearSet.add(year);
            dataMap.put(year,nums);
            sum +=  Integer.valueOf(nums);
        }
        //set转Arr
        String[] yearArr = new String[yearSet.size()];
        yearSet.toArray(yearArr);
        String[] dataArr = new String[yearSet.size()];
        String[] increaseRateArr = new String[yearSet.size()];
        //每一年都没有数据
        if(dataArr.length==0){
            resultMap.put("name",null);
            resultMap.put("xAxis",null);
            resultMap.put("data",null);
            resultMap.put("increaseRate",null);
            return resultMap;
        }
        increaseRateArr[0]="0";
        for(int i=0,len=dataArr.length;i<len;i++){
            dataArr[i]=dataMap.get(yearArr[i]);
            if(i>0){
                increaseRateArr[i] = doubleformat.format((Integer.valueOf(dataArr[i])-Integer.valueOf(dataArr[i-1]))/Float.valueOf(dataArr[i]));
            }
        }
        resultMap.put("name",DVConstants.INCREASE_MEMBER_LEGEND_NAME);
        resultMap.put("xAxis",yearArr);
        resultMap.put("data",dataArr);
        resultMap.put("increaseRate",increaseRateArr);
        return resultMap;
    }
    /**
     * @Description 获取全司复购会员数
     * @return
     * @author yangjun
     * @Date 2016年10月20日 上午9:54:42
     */
    public Map<String,Object> getAllRePurchaseMember(String siteName,String officeName){
        if(StringUtils.isNotEmpty(siteName)){
            siteName = OrderSourceTypeEnum.getOrderName(siteName);
        }
        List<Map<String,Object>> allIncreasedMemberList = memberAnalysisMapper.queryAllRePurchaseMember(siteName,officeName);
        return handleRepurchaseMemberEveryYear(allIncreasedMemberList);
    }

    public Map<String,Object> handleRepurchaseMemberEveryYear(List<Map<String,Object>> list){
        Map<String,Object> resultMap = Maps.newHashMap();
        Map<String,String> dataMap = Maps.newHashMap();
        Map<String,String> rateDataMap = Maps.newHashMap();

        //排序好的set集合用来存放年份
        Set<Integer> yearSet = Sets.newTreeSet();
        String year = null,nums = null,repurchaseRate=null;
        for(Map<String,Object> tmpMap : list){
            year = tmpMap.get("YEAR").toString();
            nums = tmpMap.get("NUMS").toString();
            repurchaseRate = tmpMap.get("REPURCHASE_RATE").toString();

            yearSet.add(Integer.valueOf(year));
            dataMap.put(year,nums);
            rateDataMap.put(year, repurchaseRate);
        }
        //set转Arr
        String[] yearArr = new String[yearSet.size()];
        int index = 0;
        for(Integer item : yearSet){
            yearArr[index++] = String.valueOf(item);
        }
        String[] dataArr = new String[yearSet.size()];
        //每一年都没数据
        if(dataArr.length==0){
            resultMap.put("name",null);
            resultMap.put("xAxis",null);
            resultMap.put("data",null);
            resultMap.put("repurchaseRate",null);
            return resultMap;
        }
        String[] repurchaseRateArr = new String[yearSet.size()];
        for(int i=0,len=dataArr.length;i<len;i++){
            dataArr[i]=dataMap.get(yearArr[i]);
            repurchaseRateArr[i]=rateDataMap.get(yearArr[i]);
        }
        resultMap.put("name",DVConstants.REPURCHASE_MEMBER_LEGEND_NAME);
        resultMap.put("xAxis",yearArr);
        resultMap.put("data",dataArr);
        resultMap.put("repurchaseRate",repurchaseRateArr);
        return resultMap;
    }
    /**
     * @Description 根据平台或者科室获取历史新增会员数表格
     * @param flag
     * @return
     * @author yangjun
     * @Date 2016年10月20日 上午9:29:34
     */
    public Map<String,Object> getMemberSituation(String flag,String siteName){
        if(StringUtils.isNotEmpty(siteName)){
            siteName = OrderSourceTypeEnum.getOrderName(siteName);
        }
        Map<String,Object> increasedMemberResultMap = Maps.newTreeMap();
        String dimensionName = null;
        //排序好的set集合用来存放年份
        Set<String> yearSet = Sets.newTreeSet();
        //根据flag设置不同平台或不同科室的map，存放每一年的会员数
        Map<String,List<Map<String, String>>> orderSourceOrOfficesMap = Maps.newTreeMap();

        String year = null;
        String nums = null;
        List<String[]> memberNumsByOrderSourceList = Lists.newArrayList();

        List<Map<String,Object>> queryMemberList = null;
        if("ORDERSOURCE".equals(flag)){
            dimensionName = "平台";
            //查询平台新增会员
            queryMemberList = memberAnalysisMapper.queryPlatFormIncreasedMember();
        }else if("OFFICES".equals(flag)){
            dimensionName = "科室";
            //查询科室新增会员
            queryMemberList = memberAnalysisMapper.queryOfficesIncreasedMember(siteName);
        }

        for(Map<String,Object> increasedMemberMap : queryMemberList){
            Map<String,String> tmpMap = Maps.newHashMap();
            year = increasedMemberMap.get("YEAR").toString();
            nums = increasedMemberMap.get("NUMS").toString();
            tmpMap.put("year", year);
            tmpMap.put("nums", nums);

            List<Map<String,String>> tmpList = null;
            int orderSource = 0;
            String officeName = null;
            String orderSourceName = null;

            if("ORDERSOURCE".equals(flag)){
                //查询平台新增会员
                orderSource = Integer.valueOf(increasedMemberMap.get("ORDERSOURCE").toString());
                orderSourceName = OrderSourceTypeEnum.getOrderSource(orderSource).getName();
                //构建平台Map
                tmpList = orderSourceOrOfficesMap.get(orderSourceName);
            }else if("OFFICES".equals(flag)){
                officeName = increasedMemberMap.get("TYPENAME").toString();
                //查询科室新增会员
                tmpList =  orderSourceOrOfficesMap.get(officeName);
            }
            if(tmpList==null){
                tmpList = Lists.newArrayList();
                tmpList.add(tmpMap);
            }else{
                tmpList.add(tmpMap);
            }
            //添加年份
            yearSet.add(year);
            if("ORDERSOURCE".equals(flag)){
                orderSourceOrOfficesMap.put(orderSourceName, tmpList);
            }else if("OFFICES".equals(flag)){
                orderSourceOrOfficesMap.put(officeName, tmpList);
            }
        }
        //set转arr
        String[] yearArr = new String[yearSet.size()];
        yearSet.toArray(yearArr);
        Arrays.sort(yearArr,new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                Integer n1 = Integer.valueOf(o1);
                Integer n2 = Integer.valueOf(o2);
                if(n1<n2){
                    return 1;
                }else if(n1>n2){
                    return -1;
                }else{
                    return 0;
                }
            }
        });
        //合计数组
        String[] totalArr = new String[yearArr.length+2];
        //标题数组
        String[] titleArr = new String[2];
        titleArr[0]=dimensionName;
        titleArr[1]="合计";
        for(Map.Entry<String,List<Map<String, String>>> entry :orderSourceOrOfficesMap.entrySet()){
            List<Map<String, String>> dataList = (List<Map<String, String>>)entry.getValue();
            Map<String,String> yearNumsMap = Maps.newHashMap();
            int sum = 0;
            //存放该平台每一年的会员数
            for(Map<String, String> dataMap: dataList){
                yearNumsMap.put(dataMap.get("year"),dataMap.get("nums"));
            }
            //从第三列才是具体每一年的数据
            String[] DataArr = new String[yearArr.length+2];
            DataArr[0] = entry.getKey();
            //有些平台可能该年没有新增会员则置为零
            for(int i = 0,len=yearArr.length ;i < len;i++ ){
                String members = yearNumsMap.get(yearArr[i]);
                if(StringUtils.isNotEmpty(members)){
                    DataArr[i+2] = members;
                }else{
                    DataArr[i+2] = "0";
                }
            }
            //每个平台的求和
            for(int i = 2,len=DataArr.length ;i < len;i++ ){
                sum += Integer.valueOf(DataArr[i]);
            }
            DataArr[1] = String.valueOf(sum);
            //组装平台数据
            memberNumsByOrderSourceList.add(DataArr);
        }
        //计算合计，遍历年份，每次循环平台list针对特定年份进行求和
        totalArr[0] = "合计";
        for(int lineIndex=1,len=totalArr.length;lineIndex<len;lineIndex++ ){
            int columnTotal = 0;
            for(int i=0;i<memberNumsByOrderSourceList.size();i++){
                columnTotal+= Integer.valueOf(memberNumsByOrderSourceList.get(i)[lineIndex]);
            }
            totalArr[lineIndex]  = String.valueOf(columnTotal);
        }
        //排序
        Collections.sort(memberNumsByOrderSourceList,new Comparator<String[]>() {
            @Override
            public int compare(String[] o1, String[] o2) {
                int current = Integer.valueOf(o1[1]);
                int concast = Integer.valueOf(o2[1]);
                if(current<concast){
                    return 1;
                }else if(current>concast){
                    return -1;
                }else{
                    return 0;
                }
            }
        });
        //将合计的数组插入的第一行
        increasedMemberResultMap.put("sum", totalArr);
        increasedMemberResultMap.put("data", memberNumsByOrderSourceList);
        increasedMemberResultMap.put("title", ArrayUtils.addAll(titleArr, yearArr));
        return increasedMemberResultMap;
    }

    /**
     * @Description 获取顶部全司会员数据（表格，饼图，柱状图）
     * @return
     * @author yangjun
     * @Date 2016年10月20日 下午2:20:40
     */
    public Map<String,Object> getCompanySituation(){
        Map<String,Object> resultMap = Maps.newHashMap();
        //柱状图的数据
        int[] memberArr = new int[5];
        Map<String,Object> barMap = Maps.newHashMap();
        //饼图的数据
        Map<String,Object> pieMap = Maps.newHashMap();
        List<Map<String,Object>> pieDataList = Lists.newArrayList();

        //全平台会员数去重,天猫会员数,天猫RX会员数
        int allPlatformMember = 0;
        int tmallMember = 0;
        int tmallRxMember = 0;
        //计算不同平台的会员数去重以及占比
        List<Map<String,Object>> platformList = memberAnalysisMapper.queryAllMemberByPlatform();
        for(Map<String,Object> map : platformList){
            String platformName = map.get("ORDERSOURCE").toString();
            int num = Integer.valueOf(map.get("USER_CNT").toString());
            if("全司".equals(platformName)){
                allPlatformMember = num;
            }else if("天猫".equals(platformName)){
                tmallMember = num;
            }else if("天猫RX".equals(platformName)){
                tmallRxMember = num;
            }
        }
        resultMap.put(DVConstants.ALL_PLATFORM_MEMBER, allPlatformMember);
        //获取其他平台会员数以及占比
        for(Map<String,Object> map : platformList){
            Map<String,Object> dataMap = Maps.newHashMap();
            int nums = Integer.valueOf(map.get("USER_CNT").toString());
            String rate = doubleformat.format(nums/(float)allPlatformMember);
            //组装会员数以及占比
            dataMap.put(DVConstants.MEMBER_NAME, nums);
            dataMap.put(DVConstants.MEMBER_RATE, rate);
            //获取平台名称
            String platName = map.get("ORDERSOURCE").toString();
            if("自建".equals(platName)){
                memberArr[2]=nums;
                resultMap.put(DVConstants.OWN_PLATFORM_NAME,dataMap);
            }else if("天猫总".equals(platName)){
                resultMap.put(DVConstants.TMALL_PLATFORM_NAME,dataMap);
            }else if("第三方".equals(platName)){
                memberArr[3]=nums;
                resultMap.put(DVConstants.THIRD_PLATFORM_NAME,dataMap);
            }else if("其他".equals(platName)){
                memberArr[4]=nums;
                resultMap.put(DVConstants.OTHER_PLATFORM_NAME,dataMap);
            }
        }
        //构建柱状图需要的数据
        memberArr[0]=tmallMember;
        memberArr[1]=tmallRxMember;
        barMap.put("data", memberArr);
        barMap.put("name", DVConstants.MEMBER_LEGEND_NAME);
        barMap.put("xAxis", DVConstants.MEMBER_BAR_XAXIS);
        resultMap.put("bar", barMap);

        //构建饼图需要的数据
        for(int i = 0,len=DVConstants.MEMBER_BAR_XAXIS.length ; i < len ; i++){
            Map<String,Object> pieDataMap = Maps.newHashMap();
            pieDataMap.put("name",DVConstants.MEMBER_BAR_XAXIS[i]);
            pieDataMap.put("value", memberArr[i]);
            pieDataList.add(pieDataMap);
        }
        pieMap.put("data", pieDataList);
        pieMap.put("lengend", DVConstants.MEMBER_BAR_XAXIS);
        pieMap.put("name", DVConstants.MEMBER_LEGEND_NAME);
        resultMap.put("pie", pieMap);
        return resultMap;
    }
}
